<template name="pyh-ps">
	<view v-if="editing">
		<view class="pyh-ps-box" ref="pyhPsBox" :style="[pyhPsBoxStyle]">
			<view class="pyh-ps-header">
				<text class="psIconFont psIconFont-close pyh-ps-cancel" @tap.stop="cancelPs"></text>
				<view class="pyh-ps-title">{{pageStyle.title||'编辑图片'}}</view>
			</view>
			<view class="pyh-ps-canvasBox" id="pyh-ps-canvasBox" @tap.stop="closeEditPopup">
				<canvas type="2d" id="pyh-ps" canvas-id="pyh-ps" class="pyh-ps-canvas" :hidpi="true" @touchstart="canvasTouchStart" @touchmove="canvasTouchMove" :style="[pyhCanvasStyle]">
					<cover-view :class="['labelList',{'labelSelected':editGroup.label.selectIndex==l}]" v-for="(label,l) in editGroup.label.data" :key="l" :style="{
						left:label.x+'px',top:label.y+'px',height:editGroup.label.labelStyle.height
					}" @touchstart="labelSelect($event,l)" @touchmove="labelTouchMove">
						<cover-view class="labelDotBox"><cover-view class="labelDot"></cover-view></cover-view>
						<cover-view class="labelTextBox" :style="{'height':editGroup.label.labelStyle.height}">
							<cover-view class="labelText" :style="{'height':editGroup.label.labelStyle.height,'line-height':editGroup.label.labelStyle.height,'padding': editGroup.label.labelStyle.padding,'color':editGroup.label.labelStyle.color,'font-size':editGroup.label.labelStyle.fontSize}">{{label.text}}</cover-view>
							<cover-image class="labelIcon" :style="{'width':editGroup.label.labelStyle.height,'height':editGroup.label.labelStyle.height}" :src="editGroup.label.labelStyle.icon" v-if="editGroup.label.labelStyle.icon"></cover-image>
						</cover-view>
						<cover-view class="psIconFont labelRemove" @touchstart.stop="labelRemove(l)" v-if="editGroup.label.selectIndex==l">&#xe610;</cover-view>
					</cover-view>
				</canvas>
				<canvas type="2d" id="pyh-ps-hide" canvas-id="pyh-ps-hide" :hidpi="true" class="pyh-ps-canvas pyh-ps-canvas-hide" :style="[pyhCanvasStyle]"></canvas>
			</view>
			<view class="editPopup editPopup-color" v-show="editGroup.color.editing">
				<view class="colorEditList" v-for="(cItem,cIndex) in editGroup.color.options" :key="cIndex">
					<view class="colorEditLabel">{{cItem.label}}</view>
					<slider class="colorEditSlider" @change="colorSliderChange" :data-index="cIndex"
						:value="cItem.value" :step="cItem.step" :min="cItem.min" :max="cItem.max" :show-value="true"
						:activeColor="pageStyle.mainColor" block-size="20" />
				</view>
			</view>
			<view class="editPopup editPopup-filter" v-show="editGroup.filter.editing">
				<scroll-view scroll-x="true" class="scrollWrapper filterWrapper">
					<view :class="['filterEditList',{'filterEditList-ac':editGroup.filter.active==fItem.type}]" v-for="(fItem,fIndex) in editGroup.filter.options" :key="fIndex"
						@tap="selectFilter(fItem.type,fItem.label)">
						{{fItem.label}}
					</view>
				</scroll-view>
			</view>
			<view class="pyh-ps-editBox">
				<view scroll-x="true" :enable-flex="true" class="pyh-ps-editGroup">
					<view class="pyh-ps-editItem" :style="{'color':editType==key&&editGroup[editType].editing?pageStyle.mainColor:'#333333'}" v-for="(value,key) in editGroup" :key="key"
						@tap.stop="editItem(key+'')">
						<text :class="['psIconFont','psIconFont-'+key]"></text>
						<text class="pyh-ps-editText">{{value.label}}</text>
					</view>
				</view>
				<view class="pyh-ps-submitBtn" :style="pageStyle.submit.style||''" @tap.stop="submitPs">{{pageStyle.submit.text||'保存'}}</view>
			</view>
			
		</view>
	</view>
</template>

<script>
	let domModule = null;
	// #ifdef APP-NVUE
	domModule = weex.requireModule('dom')
	// #endif
	var platform = "h5";
	//#ifdef H5
	platform = "h5"
	//#endif
	//#ifdef APP-PLUS
	platform = "app"
	//#endif
	//#ifdef MP
	platform = "mp"
	//#endif
	
	var dpr = uni.getSystemInfoSync().pixelRatio;
	var canvas,canvas2;
	var ctx,ctx2;
	var image,image2;
	var imgData,imgData2;
	
	export default {
		name: "pyh-ps",
		props: {
			config: {
				type: Object,
				default () {
					return {}
				}
			},
		},
		data() {
			return {
				imageInfo:{
					src:""
				},
				pageStyle:{
					title:"编辑图片",
					background:"#000000",
					mainColor: getApp()?.globalData?.mainColor || "#FF3636",
					cancel:{
						style:{}
					},
					submit:{
						text:"保存",
						style:{}
					},
					canvasStyle:{}
				},
				navigationStyle:uni.getSystemInfoSync().windowHeight==uni.getSystemInfoSync().screenHeight?'custom':'default',
				imgSize:{},
				zIndexToggleShow:true,
				canvasType: '',
				canvasStyle: {},
				initEditGroup:{
					label: {
						label:"标签",
						editing: false,
						selectIndex:-1,
						labelStyle:{
							height:"50rpx",
							color:"white",
							fontSize:"10px",
							padding:"0 14rpx",
							icon:""
						},
						customEvent: true,
						data: []
					},
					color: {
						label:"调节",
						editing: false,
						options: [
							{key: 'bright',label: "亮度",step: 5,min: 0,max: 100,value: 50,initVal:50},
							{key: 'opacity',label: "透明度",step: 1,min: 0,max: 100,value: 0,initVal:0},
							{key: 'contrast',label: "对比度",step: 1,min: 0,max: 100,value: 0,initVal:0},
						]
					},
					filter: {
						label:"滤镜",
						editing: false,
						active:0,
						options: [
							{type: '0',label: '原图'},
							{type: '1',label: '黑白调'},
							{type: '2',label: '灰色调'},
							{type: '3',label: '反转'},
							{type: '4',label: '复古'},
							{type: '5',label: '浮雕'},
							{type: '6',label: '雾化'},
							{type: '7',label: '毛玻璃'},
							{type: '8',label: '模糊'}
						]
					},
					mosaic: {
						label:"马赛克",
						editing:false,
						size:20,
						timer:0,
						touchTimer:10
					},
					crop: {
						label:"裁剪",
						customEvent: true
					},
					text: {
						label:"文字",
						editing: false,
						data: []
					},
					chartlet: {
						label:"贴图",
						options: [
							"/static/logo.png"
						],
						editing: false
					}
				},
				editType: "",
				editGroup: {}
			}
		},
		computed:{
			pyhPsBoxStyle(){
				let style = {}
				if(!this.zIndexToggleShow){
					style = {
						left:-this.canvasStyle.width+'px',
						top:-this.canvasStyle.height+'px'
					}
				}else{
					style = {'background':(this.pageStyle.background||'#000000')}
				}
				if(this.navigationStyle=="custom"){
					style['padding-top'] = uni.getSystemInfoSync().statusBarHeight+"px"
				}
				return style
			},
			editing(){return !!this.imageInfo.path},
			pyhCanvasStyle(){
				let canvasStyle = {};
				for(let i in this.canvasStyle){
					if((i=='width'||i=='height')&&typeof this.canvasStyle[i] == "number"){
						canvasStyle[i]=this.canvasStyle[i]+"px"
					}else{
						canvasStyle[i]=this.canvasStyle[i]
					}
				}
				return canvasStyle
			}
		},
		watch: {
			config: {
				handler(newObj, oldObj) {
					this.initConfig(newObj)
				},
				immediate: true,
				deep: true
			}
		},
		created() {
			// #ifdef MP-WEIXIN
			this.canvasType = '2d'
			// #endif
			if(!this.canvasType)dpr=1
			dpr = Math.ceil(dpr)
			
			domModule&&domModule.addRule('fontFace', {
				'fontFamily': 'psIconFont',
				'src': "url('https://at.alicdn.com/t/c/font_4174492_96rntk2ija.ttf?t=1693453042640.ttf')"
			})
		},
		methods: {
			initConfig(config) {
				let that = this;
				for(let i in config){
					if(i=="canvasStyle"){
						if(config[i]&&config[i].height){
							for(let s in config[i]){
								if(typeof config[i][i]=="string"&&config[i][s].includes("px")){
									config[i][s] = this.getNum(config[i][s])
								}
								let boxTop = this.navigationStyle=="custom"?uni.getSystemInfoSync().statusBarHeight:0;
								let maxWidth = uni.getSystemInfoSync().windowWidth;
								let maxHeight = uni.getSystemInfoSync().windowHeight-boxTop-parseInt((110+88) * uni.getSystemInfoSync().windowWidth / 750);
								if(s=="width"&&config[i][s]>maxWidth){
									config[i][s] = maxWidth
								}
								if(s=="height"&&config[i][s]>maxHeight){
									config[i][s] = maxHeight
								}
							}
							this.canvasStyle = Object.assign(this.canvasStyle,config[i])
						}else{
							this.canvasStyle={width:"100%",height:"100%"}
						}
					}else if(i=="editGroup"){
						config[i].forEach(item => {
							let type = item.type;
							if (type) {
								this.initEditGroup[type] = Object.assign(this.initEditGroup[type],item)
								this.editGroup[type] = JSON.parse(JSON.stringify(this.initEditGroup[type]))
							}
						})
					}else{
						if(typeof this.pageStyle[i]=="object"){
							this.pageStyle[i] = Object.assign(this.pageStyle[i],config[i])
						}else{
							this.pageStyle[i] = config[i]
						}
					}
				}
			},
			chooseImg(callback) {
				let that = this;
				function imgReturn(url,callback){
					for(let i in that.editGroup){
						that.editGroup[i] = JSON.parse(JSON.stringify(that.initEditGroup[i]));
					}
					that.initImage(url)
					callback&&callback(url)
				}
				if (uni.canIUse("chooseMedia")) {
					return uni.chooseMedia({
						count: 1,
						mediaType: ['image'],
						sizeType:['original'],
						success: (res) => {
							imgReturn(res.tempFiles[0].tempFilePath,callback);
						},
						fail(err){
							console.error(err)
							uni.showToast({
								title:"选择图片失败",
								icon:"none"
							})
						}
					});
				}
				uni.chooseImage({
					count: 1,
					success: (res) => {
						imgReturn(res.tempFiles[0].path,callback);
					},
					fail(err){
						console.error(err)
						uni.showToast({
							title:"选择图片失败",
							icon:"none"
						})
					}
				});
				
			},
			setEdit(data,type,key='data'){
				this.editGroup[type][key]=data
				if(type=="label"){
					this.editGroup[type][key] = this.editGroup[type][key].length?this.editGroup[type][key].map((item,index)=>{
						return Object.assign({
							x:this.canvasStyle.width/3,
							y:this.canvasStyle.height/3+index*this.getNum(this.editGroup[type].labelStyle.height)
						},item)
					}):[]
				}
				this.$forceUpdate()
			},
			async getImageInfo(url) {
				let info = {};
				if(url.startsWith("http"))url = await new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success(e) {resolve(e.tempFilePath)},
						fail(err) {
							url=""
							console.error("下载图片失败", err)
						}
					})
				})
				if(!url)return;
				info = await new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success(info) {resolve(info);},
						fail(err) {
							console.error("获取图片失败", err)
						}
					})
				})
				return info
			},
			async initImage(url) {
				let that = this;
				this.editGroup["filter"].active=0
				this.imageInfo = await this.getImageInfo(url)
				if(!this.imageInfo.path)return
				await new Promise((resolve) => {
					this.$nextTick(()=>{setTimeout(()=>{resolve()},200)})
				})
				let canvasSq = await new Promise((resolve) => {
					uni.createSelectorQuery().in(this).select('#pyh-ps').boundingClientRect().exec(rect=>{
						delete rect[0].dataset; 
						resolve(rect[0])
					})
				})
				this.canvasStyle = Object.assign(this.canvasStyle,canvasSq)
				canvas = await new Promise((resolve) => { uni.createSelectorQuery().in(this).select('#pyh-ps')
					.fields({ node: true, size: true }).exec((res) => {resolve(res[0].node||res[0])})});
				canvas2 = await new Promise((resolve) => { uni.createSelectorQuery().in(this).select('#pyh-ps-hide')
					.fields({ node: true, size: true }).exec((res) => {resolve(res[0].node||res[0])})});
				canvas.width = canvasSq.width * dpr;
				canvas.height = canvasSq.height * dpr;
				canvas2.width = canvas.width
				canvas2.height = canvas.height
				if(this.canvasType){
					ctx = canvas.getContext(this.canvasType||'2d')
					ctx2 = canvas2.getContext(this.canvasType||'2d')
				}else{
					ctx = uni.createCanvasContext('pyh-ps',this)
					ctx2 = uni.createCanvasContext('pyh-ps-hide',this)
				}
				ctx.scale(dpr, dpr)
				ctx2.scale(dpr, dpr)
				this.drawCanvas()
			},
			editItem(type) {
				if(this.editType&&this.editType!=type&&this.editGroup[this.editType].editing){
					this.editGroup[this.editType].editing = false
					if(this.editType=="label"){
						this.editGroup.label.selectIndex=-1
					}else if(this.editType=="mosaic"){
						this.coverData();
						this.reloadEditData()
					}
				}
				this.editType = type;
				switch (type) {
					case 'crop':
						if (this.editGroup[type].customEvent) {
							this.$emit('psEdit', {
								type,
								data: {
									src: this.imageInfo.path
								}
							})
						}else{
							uni.showToast({
								title:"暂不支持，可配置customEvent来接入其它"+this.editGroup[type].label+"插件，可参考示例项目",
								icon:"none"
							})
						}
						break;
					case 'mosaic':
						this.editGroup[type].editing = !this.editGroup[type].editing
						this.$forceUpdate()
						if(!this.editGroup[type].editing){
							this.coverData();
							this.reloadEditData()
						}else{
							this.resetImgData()
						}
						uni.showToast({
							title:"马赛克编辑已"+(this.editGroup[type].editing?"开启，开启期间屏蔽其它效果":"关闭"),
							icon:"none"
						})
						break;
					case 'label':
						this.toggleEdit()
						if(!this.editGroup[type].editing)return
						if (this.editGroup[type].customEvent) {
							this.$emit('psEdit', {
								type,
								data:this.editGroup[type].data
							})
						}else{
							uni.showToast({
								title:"暂不支持，可配置customEvent来接入其它"+this.editGroup[type].label+"插件，可参考示例项目",
								icon:"none"
							})
						}
						break;
					default:
						this.toggleEdit()
						break;
				}
			},
			closeEditPopup() {
				let noTypeArr = ['mosaic','label']
				if (this.editType&&!noTypeArr.includes(this.editType) && this.editGroup[this.editType].editing) {
					this.toggleEdit()
				}
			},
			toggleEdit() {
				if (!this.editGroup[this.editType].editing) {
					for (let i in this.editGroup) {
						this.editGroup[i].editing && (this.editGroup[i].editing = false)
					}
				}
				this.editGroup[this.editType].editing = !this.editGroup[this.editType].editing
				if (!this.editGroup[this.editType].editing)this.editType = ""
				this.$forceUpdate()
			},
			colorSliderChange(e) {
				let that = this;
				let index = e.currentTarget.dataset.index;
				let key = this.editGroup.color.options[index].key,
					label = this.editGroup.color.options[index].label,
					val = e.detail.value;
				this.editGroup.color.options[index].value = val;
				// console.log(label, key, val)
				
				this.resetImgData()
				const data = imgData.data;
						
				let turnFun = {
					bright(val,mix=false){
						let turnVal = val*5.1-255;
						for (var i = 0; i < data.length; i += 4) {
							data[i + 0] += turnVal;
							data[i + 1] += turnVal;
							data[i + 2] += turnVal;
						}
						!mix&&this.mix()
					},
					opacity(val,mix=false){
						let turnVal = 1-val / 100;
						for (var i = 0; i < data.length; i += 4) {
							data[i + 3] = data[i + 3] * turnVal;
						}
						!mix&&this.mix()
					},
					contrast(val,mix=false){
						let turnVal =  val*2.55;
						var factor = (255 + turnVal) / (255.01 - turnVal);
						
						for (var i = 0; i < data.length; i += 4) {
							data[i] = factor * (data[i] - 128) + 128;
							data[i + 1] = factor * (data[i + 1] - 128) + 128;
							data[i + 2] = factor * (data[i + 2] - 128) + 128;
						}
						!mix&&this.mix()
					},
					mix(){
						for(let i in that.editGroup.color.options){
							if(that.editGroup.color.options[i].key!=key&&that.editGroup.color.options[i].value!=that.editGroup.color.options[i].initVal){
								this[that.editGroup.color.options[i].key](that.editGroup.color.options[i].value,true)
							}
						}
					}
				}
				if(turnFun[key]){
					turnFun[key](val)
				}else{
					return console.error("未知类型")
				}
				
				if(this.canvasType){
					ctx.putImageData(imgData,0,0)
				}else{
					ctx.restore()
					ctx.draw(false, res => {
						uni.canvasPutImageData({
							canvasId: 'pyh-ps',
							x: 0,
							y: 0,
							width: canvas.width,
							height: canvas.height,
							data,
							success(res) {
								console.log('设置' + label + '成功')
							},
							fail(err) {
								console.error(err);
							}
						}, this);
					})
				}
			},
			selectFilter(type,label) {
				// console.log(type,label)
				let that = this;
				
				if(!this.editGroup.filter.options.find((item,index)=>{return item.type==type})) {
					return console.error("未知类型")
				}
				this.editGroup["filter"].active=type
				this.$forceUpdate()
				this.resetImgData()
				const data = imgData.data;
				let w = this.canvasStyle.width,
					h = this.canvasStyle.height;
				if (type == '1') {
					for (let i = 0; i < data.length; i += 4) {
						let r = data[i];
						let g = data[i + 1];
						let b = data[i + 2];
						if (r > 255 / 2) {
							data[i] = 255
							data[i + 1] = 255
							data[i + 2] = 255
						} else if (r < 255 / 2) {
							data[i] = 0
							data[i + 1] = 0
							data[i + 2] = 0
						}
					}
				} else if (type == '2') {
					for (let i = 0; i < data.length; i += 4) {
						let r = data[i];
						let g = data[i + 1];
						let b = data[i + 2];
						let average = Math.floor((r + g + b) / 3);
						data[i] = average;
						data[i + 1] = average;
						data[i + 2] = average;
					}
				} else if (type == '3') {
					for (let i = 0, len = data.length; i < len; i += 4) {
						data[i] = 255 - data[i];
						data[i + 1] = 255 - data[i + 1]
						data[i + 2] = 255 - data[i + 2];
					}
				} else if (type == '4') {
					for (let i = 0; i < data.length; i += 4) {
						let r = data[i];
						let g = data[i + 1];
						let b = data[i + 2];
						data[i] = (r * 0.393) + (g * 0.769) + (b * 0.189);
					}
				} else if (type == '5') {
					for (let i = h; i > 0; i--) { // 行
						for (let j = w; j > 0; j--) { // 列
							for (let k = 0; k < 3; k++) {
								let num = (i * w + j) * 4 + k;
								let numUp = ((i - 1) * w + j) * 4 + k;
								let numDown = ((i + 1) * w + j) * 4 + k;
								data[num] = data[num] - data[numUp - 4] + 128;
							}
						}
					}
				} else if (type == '6') {
					for (let i = h; i > 0; i--) { // 行
						for (let j = w; j > 0; j--) { // 列
							let num = (i * w + j) * 4;
							if (Math.random() < 0.1) {
								data[num] = 255;
								data[num + 1] = 255;
								data[num + 2] = 255;
							}
						}
					}
				} else if (type == '7') {
					for (let i = 0; i < h; i++) {
						for (let j = 0; j < w; j++) {
							for (let k = 0; k < 3; k++) {  
								let num = (i * w + j) * 4 + k;
								let rand = Math.floor(Math.random() * 10) % 3;
								let num2 = ((i + rand) * w + (j + rand)) * 4 + k;
								data[num] = data[num2]
							}
						}
					}
				} else if (type == '8') {
					let data1 = data;
					let data2 = data;
					for (let i = 0; i < h; i++) { // 行
						for (let j = 0; j < w; j++) { // 列
							for (let k = 0; k < 3; k++) {
								let num = (i * w + j) * 4 + k;
								let numUp = ((i - 1) * w + j) * 4 + k;
								let numDown = ((i + 1) * w + j) * 4 + k;
								data1[num] = (data2[numUp - 4] + data2[numUp] + data2[numUp + 4] + data2[num - 4] + data2[num] + data2[num + 4] + data2[numDown - 4] + data2[numDown] + data2[numDown + 4]) / 9;
							}
						}
					}
				}
				
				if(this.canvasType){
					ctx.putImageData(imgData,0,0)
				}else{
					ctx.restore()
					ctx.draw(false, res => {
						uni.canvasPutImageData({
							canvasId: 'pyh-ps',
							x: 0,
							y: 0,
							width: canvas.width,
							height: canvas.height,
							data,
							success(res) {
								console.log('设置' + label + '成功')
							},
							fail(err) {
								console.error(err);
							}
						}, this);
					})
				}
			},
			labelRemove(index){
				let that = this;
				uni.showModal({
					title:"温馨提示",
					content:"确认移除该标签？",
					confirmColor:this.pageStyle.mainColor,
					success(res) {
						if(res.confirm){
							that.editGroup.label.selectIndex=-1
							that.editGroup.label.data.splice(index,1)
							that.$forceUpdate()
						}
					}
				})
			},
			labelSelect(e,index){
				this.editGroup.label.selectIndex = index
				
				let x=parseInt(e.touches[0].pageX-this.canvasStyle.left);
				let y=parseInt(e.touches[0].pageY-this.canvasStyle.top);
				this.editGroup.label.data[this.editGroup.label.selectIndex] = Object.assign(this.editGroup.label.data[this.editGroup.label.selectIndex],{x,y})
				if(this.editType!="label"){
					this.editType="label"
					this.toggleEdit()
				}
				this.$forceUpdate()
			},
			labelTouchMove(e){
				let x=parseInt(e.touches[0].pageX-this.canvasStyle.left);
				let y=parseInt(e.touches[0].pageY-this.canvasStyle.top);
				this.editGroup.label.data[this.editGroup.label.selectIndex] = Object.assign(this.editGroup.label.data[this.editGroup.label.selectIndex],{x,y})
				this.$forceUpdate()
			},
			canvasTouchStart(e){
				let that = this;
				if(!this.editType||!this.editGroup[this.editType].editing)return false
				
				let touch = e.touches[0];
				let {x,y} = touch;
				x=parseInt(x);
				y=parseInt(y);
				// if(this.editType == "label"&&this.editGroup.label.selectIndex>-1){
				// 	this.editGroup.label.data[this.editGroup.label.selectIndex] = Object.assign(this.editGroup.label.data[this.editGroup.label.selectIndex],{x,y})
				// 	this.$forceUpdate()
				// }
			},
			canvasTouchMove(e) {
				let that = this;
				
				if(!this.editType||!this.editGroup[this.editType].editing)return false
				
				let touch = e.touches[0];
				let {x,y} = touch;
				x=parseInt(x)*dpr;
				y=parseInt(y)*dpr;
				if (this.editType == "mosaic") {
					//防抖
					if(this.editGroup["mosaic"].timer)return
					this.editGroup["mosaic"].timer=1
					setTimeout(()=>{
						this.editGroup["mosaic"].timer=0
					},this.editGroup["mosaic"].touchTimer)
					
					let size = this.editGroup["mosaic"].size||20; //马赛克尺寸，越大越模糊
					size*=dpr;
					
					const data = imgData.data;
					const data2 = imgData2.data;
					
					const color = [];
					color[0] = data2[4 * (y * canvas.width + x)];
					color[1] = data2[4 * (y * canvas.width + x) + 1];
					color[2] = data2[4 * (y * canvas.width + x) + 2];
					color[3] = data2[4 * (y * canvas.width + x) + 3];
					
					for (let k = 0; k < size; k++) {
						for (let l = 0; l < size; l++) {
							data[4 * ((y + k - size / 2) * canvas.width + (x + l - size / 2))] = color[0];
							data[4 * ((y + k - size / 2) * canvas.width + (x + l - size / 2)) + 1] = color[1];
							data[4 * ((y + k - size / 2) * canvas.width + (x + l - size / 2)) + 2] = color[2];
							data[4 * ((y + k - size / 2) * canvas.width + (x + l - size / 2)) + 3] = color[3];
						}
					}
					
					if(this.canvasType){
						ctx.putImageData(imgData,0,0)
						// console.log('设置成功	x:'+x+',y:'+y+',color:'+JSON.stringify(color))
					}else{
						uni.canvasPutImageData({
							canvasId: 'pyh-ps',
							x: 0,
							y: 0,
							width: canvas.width,
							height: canvas.height,
							data,
							success(res) {
								// console.log('设置成功	x:'+x+',y:'+y)
							},
							fail(err) {
								console.error(err);
							}
						}, this);
					}
				}
			},
			zIndexToggle(){
				this.zIndexToggleShow = !this.zIndexToggleShow;
				this.$forceUpdate()
			},
			reloadEditData(){
				let that = this;
				for(let i in this.editGroup){
					if(i=="color"){
						for(let c in that.editGroup[i].options){
							if(that.editGroup[i].options[c].value!=that.editGroup[i].options[c].initVal){
								this.colorSliderChange({
									currentTarget:{dataset:{index:c}},
									detail:{value:that.editGroup[i].options[c].value}
								})
							}
						}
					}else if(i=="filter"){
						if(this.editGroup[i].active!=0){
							let activeItem = this.editGroup[i].options.find(item=>{
								return item.type==this.editGroup[i].active})
							this.selectFilter(activeItem.type,activeItem.label)
						}
					}
				}
			},
			resetImgData(){
				let that = this;
				if(this.canvasType){
					imgData = ctx2.getImageData(0, 0, canvas.width,canvas.height);
					ctx.putImageData(imgData,0,0)
				}else{
					uni.canvasGetImageData({
						canvasId: 'pyh-ps-hide',
						x: 0,y: 0,width: canvas.width,height: canvas.height,
						success(res) {
							imgData = res
							uni.canvasPutImageData({
								canvasId: 'pyh-ps',
								x: 0,
								y: 0,
								width: canvas.width,
								height: canvas.height,
								data:imgData.data,
								success(res) {
									console.log('还原成功')
								},
								fail(err) {
									console.error(err);
								}
							}, that);
						},
						fail(err) {
							console.error("无法获取图片信息。err:",err);
							uni.showToast({
								title:"无法获取图片信息",
								icon:"none"
							})
						}
					}, that)
				}
			},
			coverData(){
				let that = this;
				if(this.canvasType){
					imgData = ctx.getImageData(0, 0, canvas.width,canvas.height);
					ctx2.putImageData(imgData,0,0)
					imgData2 = ctx2.getImageData(0, 0, canvas.width,canvas.height);
				}else{
					uni.canvasGetImageData({
						canvasId: 'pyh-ps',
						x: 0,y: 0,width: canvas.width,height: canvas.height,
						success(res) {
							imgData = res
							uni.canvasPutImageData({
								canvasId: 'pyh-ps-hide',
								x: 0,
								y: 0,
								width: canvas.width,
								height: canvas.height,
								data:imgData.data,
								success(res) {
									uni.canvasGetImageData({
										canvasId: 'pyh-ps-hide',
										x: 0,y: 0,width: canvas.width,height: canvas.height,
										success(res) {
											imgData2 = res
											console.log('覆盖成功')
										}
									})
								},
								fail(err) {
									console.error(err);
								}
							}, that);
						},
						fail(err) {
							console.error("无法获取图片信息。err:",err);
							uni.showToast({
								title:"无法获取图片信息",
								icon:"none"
							})
						}
					}, that)
				}
			},
			async drawCanvas() {
				let that = this;
				let imgSize={}
				let direction = 'col';
				let ratio = this.canvasStyle.width/this.imageInfo.width;
				if(this.imageInfo.height * ratio < this.canvasStyle.height){
					ratio=this.canvasStyle.height/this.imageInfo.height
					direction='row'
				}
				if(direction=='row'){
					imgSize = {
						top:0,
						height:this.canvasStyle.height,
						width: this.imageInfo.width * ratio,
						left: -(this.imageInfo.width * ratio - this.canvasStyle.width)/2
					}
				}else{
					imgSize = {
						left:0,
						width:this.canvasStyle.width,
						height: this.imageInfo.height * ratio,
						top: -(this.imageInfo.height * ratio - this.canvasStyle.height)/2
					}
				}
				this.imgSize = imgSize;
				if(this.canvasType){
					await new Promise((resolve,reject) => {
						image = canvas.createImage()
						image.onload = () => {resolve()}
						image.src = that.imageInfo.path
					});
					await new Promise((resolve,reject) => {
						image2 = canvas2.createImage()
						image2.onload = () => {resolve()}
						image2.src = that.imageInfo.path
					});
				}
				ctx.clearRect(0, 0, canvas.width, canvas.height)
				ctx2.clearRect(0, 0, canvas.width, canvas.height)
				if(this.canvasType){
					ctx.drawImage(image, that.imgSize.left, that.imgSize.top, that.imgSize.width, that.imgSize.height)
					ctx2.drawImage(image2, that.imgSize.left, that.imgSize.top, that.imgSize.width, that.imgSize.height)
					imgData = ctx.getImageData(0, 0, canvas.width,canvas.height);
					imgData2 = ctx2.getImageData(0, 0, canvas.width,canvas.height);
				}else{
					ctx.drawImage(that.imageInfo.path, that.imgSize.left, that.imgSize.top, that.imgSize.width, that.imgSize.height)
					ctx2.drawImage(that.imageInfo.path, that.imgSize.left, that.imgSize.top, that.imgSize.width, that.imgSize.height)
					ctx.draw(false, res => {
						uni.canvasGetImageData({
							canvasId: 'pyh-ps',
							x: 0,y: 0,width: canvas.width,height: canvas.height,
							success(res) {imgData = res},
							fail(err) {
								console.error("无法获取图片信息。err:",err);
								uni.showToast({
									title:"无法获取图片信息",
									icon:"none"
								})
							}
						}, that)
					})
					ctx2.draw(false, res => {
						uni.canvasGetImageData({
							canvasId: 'pyh-ps-hide',
							x: 0,y: 0,width: canvas.width,height: canvas.height,
							success(res) {imgData2 = res},
							fail(err) {
								console.error("无法获取图片信息。err:",err);
								uni.showToast({
									title:"无法获取图片信息",
									icon:"none"
								})
							}
						}, that)
					})
				}
			},
			reInitPs(){
				imgData =null;
				imgData2 = null;
				canvas = null;
				canvas2 = null;
				ctx = null;
				ctx2 = null;
				for(let i in this.editGroup){
					this.editGroup[i] = JSON.parse(JSON.stringify(this.initEditGroup[i]))
				}
			},
			cancelPs(){
				this.reInitPs()
				this.imageInfo.path=""
			},
			submitPs(){
				let that = this;
				uni.showLoading({
					title:"图片生成中"
				})
				if(this.editType){
					this.editGroup[this.editType].editing = false
					this.editGroup[this.editType].active&&(this.editGroup[this.editType].active=0)
					this.editType=""
					this.reloadEditData()
				}
				let submitData;
				if(this.editGroup.label.data.length)submitData = this.editGroup.label.data
				setTimeout(()=>{
					uni.canvasToTempFilePath({
						x: 0,
						y: 0,
						width: this.canvasStyle.width,
						height: this.canvasStyle.height,
						destWidth: this.canvasStyle.width*2,
						destHeight: this.canvasStyle.height*2,
						canvasId: 'pyh-ps',
						canvas,
						success(res) {
							uni.hideLoading()
							that.cancelPs()
							that.$emit("psSave",res.tempFilePath,submitData)
						},
						fail(err) {
							uni.hideLoading()
							uni.showToast({
								title:"图片生成失败",
								icon:"none"
							})
							console.error(err)
						}
					},this)
				},400)
			},
			getNum(text){
				if(typeof text=="number")return text;
				if(typeof text=="string"&&text.includes("px")){
					if(text.includes("rpx")||text.includes("upx")){
						let pxRatio = uni.getSystemInfoSync().windowWidth/750;
						text = parseInt(parseFloat(text)*pxRatio);
					}else{
						text = parseFloat(text);
					}
					return text;
				}else{
					console.error("错误格式")
				}
			},
		}
	}
</script>


<style lang="scss" scoped>
	/* #ifndef APP-NVUE */
	@font-face {
	    font-family: psIconFont;
	    src: url('https://at.alicdn.com/t/c/font_4174492_96rntk2ija.ttf?t=1693453042640') format('truetype');
	}
	/* #endif */
	
	$mainColor: #FF3636 !default;
	
	.psIconFont {
	  font-family: psIconFont;
	  font-size: 17px;
	  font-style: normal;
	  color: inherit;
	}
	.psIconFont-color::after{content: "\e60b";}
	.psIconFont-filter::after{content: "\e60e";}
	.psIconFont-mosaic::after{content: "\e60c";}
	.psIconFont-crop::after{content: "\e60f";}
	.psIconFont-chartlet::after{content: "\e60a";}
	.psIconFont-text::after{content: "\e609";}
	.psIconFont-label::after{content: "\e60d";}
	.psIconFont-close::after{content: "\e610";}
	
	.pyh-ps-box {
		position: fixed;
		z-index: 997;
		top: var(--window-top);
		left: 0;
		width: 100%;
		height: calc(100% - var(--window-top));
		display: flex;
		flex-direction: column;
	}
	
	.pyh-ps-header{
		width: 100%;
		height: 88rpx;
		background-color: black;
		color: white;
		display: flex;
		justify-content: center;
		padding: 0 110rpx;
		align-items: center;
		flex-direction: row;
		position: relative;
		font-weight: bold;
		font-size: 32rpx;
		box-sizing: border-box;
	}
	
	.pyh-ps-cancel{
		width: 50rpx;height: 50rpx;color: white;font-size: 23px;
		position: absolute;left: 30rpx;top: 50%;transform: translateY(-50%);
	}
	
	.pyh-ps-editBox {
		height: 110rpx;
		background-color: white;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-right: 30rpx;
		justify-content: space-between;
	}
	.pyh-ps-submitBtn {
		font-size: 14px;
		font-weight: bold;
		border-radius: 6px;
		width: 146rpx;
		height: 64rpx;
		line-height: 64rpx;
		text-align: center;
		color: white;
		background-color: $mainColor;
	}
	
	.pyh-ps-canvasBox{
		width: 100%;
		flex: 1;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.pyh-ps-canvas {
		width: 100%;
		height: 100%;
		max-width: 100%;
		max-height: 100%;
		z-index: 2;
		position: relative;
	}
	.pyh-ps-canvas-hide {
		z-index: 1;
		opacity: 0;
		position: absolute;
		top: -2000px;
		left: -2000px;
		transform: initial;
	}

	.pyh-ps-editGroup {
		height: 100%;width: 100%;background-color: white;display: flex;justify-content: space-around;
		text-align: center;white-space: nowrap;padding: 0 30rpx;
	}
	.pyh-ps-editItem {
		color:#333333;
		flex: 1;
		display: inline-flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		min-width: 70rpx;
		margin: 0 auto;
		padding: 10rpx 0;
	}

	.pyh-ps-editText {
		font-size: 14px;
	}

	.editPopup {
		position: fixed;
		bottom: 110rpx;
		background-color: white;
		width: 100%;
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #ddd;
		box-sizing: border-box;
		z-index: 998;
	}

	.colorEditList {
		display: flex;
		align-content: center;
	}

	.colorEditLabel {
		margin: auto;
		width: 100rpx;
		font-size: 15px;
	}

	.colorEditSlider {
		flex: 1;
		margin-right: 0;
	}

	.editPopup-chartlet {}

	.scrollWrapper {
		box-sizing: border-box;
		width: 100%;
		overflow-x: auto;
		box-shadow: -10rpx 0rpx 10rpx #ccc inset;
		background-color: white;
		padding: 20rpx 0;
		white-space: nowrap;
	}
	.filterWrapper{
		height: 160rpx;
	}

	.scrollWrapper::-webkit-scrollbar {
		display: none
	}

	.chartletEditList,
	.filterEditList {
		width: 120rpx;
		height: 120rpx;
		min-width: 120rpx;
		min-height: 120rpx;
		border: solid 1px #ccc;
		margin: 0 10rpx;
		border-radius: 10rpx;
		display: inline-block;
		box-sizing: border-box;
	}

	.chartletImg {
		width: 100%;
		height: 100%;
	}

	.filterEditList {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		color: #333;
		font-size: 14px;
		font-weight: bold;
	}
	.filterEditList-ac{
		background-color: rgba(255, 0, 0, .1);
	}
	
	.labelList{
		z-index: 998;
		position: absolute;
		display: flex;
		flex-direction: row;
		align-items: center;
		transform: translateY(-50%);
		box-sizing: content-box;
		will-change: auto;
		border: none;
	}
	.labelSelected{border: 1px dashed #999;}
	// .labelBg{width: auto;height: 100%;}
	// .labelText{width: 100%;height: 100%;left: 0;top: 50%;transform: translateY(-50%); position: absolute;padding: 0 40rpx 0 40rpx;font-size: 10px;white-space: nowrap;text-overflow: ellipsis;box-sizing: border-box;}
	.labelRemove{width: 32rpx;height: 32rpx;margin-left: 10rpx;color: white;font-size: 14px;}
	.labelDotBox{width: 24rpx;height: 24rpx;background-color: rgba(0, 0, 0, .8);border-radius: 50%;display: flex;align-items: center;justify-content: center;margin-right: 15rpx;}
	.labelDot{width: 12rpx;height: 12rpx;background-color: #fff;border-radius: 50%;}
	.labelTextBox{height: 50rpx;background-color: rgba(0, 0, 0, .8);display: flex;align-items: center;border-radius: 8rpx;overflow: hidden;}
	.labelText{flex: 1;height: 50rpx;line-height: 50rpx;padding: 0 14rpx;font-size: 10px;white-space: nowrap;text-overflow: ellipsis;box-sizing: border-box;max-width: 250rpx;color: #fff;}
	.labelIcon{width: 50rpx;height: 50rpx;}
</style>